package com.click369.crm.controller;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.click369.crm.common.VerifyCodeUtils;
import com.mysql.jdbc.StringUtils;

@Controller
@RequestMapping("admin")
public class AdminController {
	
	@RequestMapping("login")
	public String login(String username,String password,String inputcode,HttpSession session){
		String code = (String)session.getAttribute("code");
		//判断验证码不是空的或者用户输入的验证码和服务端的相同
		if(!StringUtils.isNullOrEmpty(code)&&inputcode.toLowerCase().equals(code.toLowerCase())){
			Subject subject = SecurityUtils.getSubject();
			UsernamePasswordToken token = new UsernamePasswordToken(username,password,true);
			try {
				/**
				 * 可能性：1.登录成功 继续跳转页面 2.登录失败 抛异常
				 */
				subject.login(token);
				return "index";
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "login";
	}
	
	@RequestMapping("logout")
	public String logout(HttpSession session){
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "login";
	}
	
	@RequestMapping("code")
	public void code(HttpSession session,HttpServletRequest request,HttpServletResponse response){
		try{
			//生成四位的验证码
			String code = VerifyCodeUtils.generateVerifyCode(4);
			session.setAttribute("code", code);
			ServletOutputStream outputStream = response.getOutputStream();
			//设置是否缓存，缓存时间
			response.setHeader("Expires", "0");
			//设置验证码的类型
			response.setContentType("image/jpeg");
			//设置验证码宽，高，响应验证码
			VerifyCodeUtils.outputImage(90,30,outputStream,code);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
}
